import {
	createRouter,
	type RouteRecordRaw,
	type NavigationGuardNext,
	type RouteLocationNormalized,
	createWebHashHistory
} from 'vue-router'

const routes: RouteRecordRaw[] = [
	{
		path: '/',
		name: '默认路径',
		redirect: '/login'
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('../views/login.vue')
	},
	{
		path: '/showImg',
		name: 'showImg',
		component: () => import('../views/showImg.vue')
	},
	{
		path: '/main',
		name: 'main',
		redirect: '/home',
		component: () => import('../views/main.vue'),
		children: [
			{
				path: '/home',
				name: 'home',
				component: () => import('../views/home.vue')
			},
			{
				path: '/about',
				name: 'about',
				component: () => import('../views/about.vue')
			},
			{
				path: '/contact',
				name: 'contact',
				component: () => import('../views/contact.vue')
			}
		]
	}
]

const router = createRouter({
	history: createWebHashHistory(),
	routes
})

router.beforeEach(
	(to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
		const token = localStorage.getItem('token')
		if (token) {
			// 如果有 token，无论当前要访问的是什么路由，都进入首页
			if (['/', '/login'].includes(to.path)) {
				// 如果当前要访问登录页，重定向到首页
				next('/main')
			} else {
				next()
			}
		} else {
			next()
		}
	}
)

export default router
